<template>
	<div class="search">
		<Row>
			<Col>
			<Card>
				<Row @keydown.enter.native="handleSearch">
					<Form ref="searchForm" :model="searchForm" inline :label-width="110" class="search-form">
						<Form-item label="展馆号" prop="hallNo">
							<Input type="text" v-model.trim="searchForm.hallNo" placeholder="请输入展馆号" clearable style="width: 200px" />
						</Form-item>

						<Form-item style="margin-left:-35px;" class="br">
							<Button @click="handleSearch" type="primary" icon="ios-search">搜索</Button>
							<Button @click="handleReset">重置</Button>

						</Form-item>
					</Form>
				</Row>
				<Row class="operation">
					<Button @click="add" type="primary" icon="md-add">添加</Button>
					<Button @click="delAll" icon="md-trash">批量删除</Button>
					<Button @click="getDataList" icon="md-refresh">刷新</Button>
					<circleLoading v-if="operationLoading" />
				</Row>
				<Row>
					<Alert show-icon>
						已选择 <span class="select-count">{{selectCount}}</span> 项
						<a class="select-clear" @click="clearSelectAll">清空</a>
					</Alert>
				</Row>
				<Row>
					<Table :loading="loading" border :columns="columns" :data="data" ref="table" sortable="custom" @on-sort-change="changeSort"
					 @on-selection-change="changeSelect"></Table>
				</Row>
				<Row type="flex" justify="end" class="page">
					<Page :current="pageNumber" :total="total" :page-size="pageSize" @on-change="changePage" @on-page-size-change="changePageSize"
					 :page-size-opts="[10,20,50]" size="small" show-total show-elevator show-sizer></Page>
				</Row>
			</Card>
			</Col>
			
		</Row>
		<Modal :title="modalTitle" v-model="modalVisible" :mask-closable='false' :width="600">
			<Form ref="form" :model="form" :label-width="100" :rules="formValidate">
				<FormItem label="展馆号" prop="hallNo">
					<Input v-model.trim="form.hallNo"  placeholder="请输入展馆号" style="width:350px" :maxlength=10  />
				</FormItem>
				<FormItem label="描述" prop="labelCn">
					<Input v-model.trim="form.labelCn"  placeholder="请输入描述" style="width:350px" :maxlength=100  />
				</FormItem>
				<FormItem label="描述(英文)" prop="labelEn">
					<Input v-model.trim="form.labelEn"  placeholder="请输入描述(英文)" style="width:350px" :maxlength=100  />
				</FormItem>
				<FormItem label="展位图"  prop="imageUrl">
					<Input v-model.trim="form.imageUrl" :maxlength=200 placeholder="请输入展位图链接" style="width:350px" @on-change="inputImage" />
					<Row style="margin-top:10px;">
						<Col span="4">
							<Upload ref="upload" :show-upload-list="false" :default-file-list="uploadList" :on-success="handleSuccess"
							 :on-error="handleError" :format="['jpg','jpeg','png','gif']" :max-size="5120" :on-format-error="handleFormatError"
							 :on-exceeded-size="handleMaxSize" :before-upload="handleBeforeUpload" type="drag" :action="uploadFileUrl"
							 :headers="accessToken" style="display: inline-block;width:58px;">
								<div style="width: 58px;height:58px;line-height: 58px;">
									<Icon type="md-camera" size="20"></Icon>
								</div>
							</Upload>
						</Col>
						<Col span="20">
							
							<div class="upload-list" v-for="item in uploadList" :key="item.url">
								<template>
									<img :src="item.url" style="width:200px;">
								</template>
							</div>
						</Col>
						
					</Row>
				</FormItem>
			</Form>
			<div slot="footer">
				<Button type="text" @click="modalVisible=false">取消</Button>
				<Button type="primary" :loading="submitLoading" @click="handleSubmit">提交</Button>
			</div>
		</Modal>
		<Modal
		  v-model="picVisible"
		  :title="picTitle"
		  draggable footer-hide>
		  <img :src="imageUrl" alt="无效的图片链接" style="width: 100%;margin: 0 auto;display: block;">
		  
		</Modal>
	</div>
</template>

<script>
	import circleLoading from "@/views/my-components/circle-loading.vue";

	import {
		addHall,
		editHall,
		getHallList,
		deleteHall,
		uploadFile,
	} from "@/api/index";
	export default {
		name: "hall-manage",
		components: {
			circleLoading,
		},
		data() {
			return {
				picVisible:false,
				picTitle:'',
				imageUrl:'',
				/*图片上传部分开始*/
				accessToken: {},
				uploadFileUrl: uploadFile,
				uploadList: [],
				/*图片上传部分结束*/
				loading: true, // 表单加载状态
				operationLoading: false, // 操作加载状态
				modalType: 0, // 添加或编辑标识
				modalVisible: false, // 添加或编辑显示
				modalTitle: "", // 添加或编辑标题
				searchForm: { // 搜索框初始化对象
					pageNumber: 1, // 当前页数
					pageSize: 10, // 页面大小
					sort: "hallNo", // 默认排序字段
					order: "asc", // 默认排序方式
				},
				form: { // 添加或编辑表单对象初始化数据
					hallNo: "",
					imageUrl: '',
					labelCn:'',
					labelEn:'',
				},
				// 表单验证规则
				formValidate: {
					hallNo: [{
						required: true,
						trigger: "blur",
						message: "请输入展馆号"
					}],
				


				},
				submitLoading: false, // 添加或编辑提交状态
				selectList: [], // 多选数据
				selectCount: 0, // 多选计数
				columns: [
					// 表头
					{
						type: "selection",
						width: 60,
						align: "center"
					},
					{
						type: "index",
						width: 60,
						align: "center"
					},
					{
						title: "展馆号",
						key: "hallNo",
						minWidth: 120,
					},
					{
						title: "描述",
						key: "labelCn",
						minWidth: 120,
					},
					{
						title: "描述（英文）",
						key: "labelEn",
						minWidth: 120,
					},
					{
					  title: "缩略图(点击预览)",
					  key: "imageUrl",
					  width: 130,
					  align: "center",
					  render: (h, params) => {
					  
					      return h("img", {
					        attrs: {
					          src: params.row.imageUrl,
					          alt: "加载图片失败"
					        },
					        style: {
					          cursor: "pointer",
					          width: "80px",
					          height: "60px",
					          margin: "10px 0",
					          "object-fit": "contain"
					        },
					        on: {
					          click: () => {
					            this.showImage(params.row);
					          }
					        }
					      });
					    
					  }
					},
					{
						title: "创建时间",
						key: "createTime",
						minWidth: 160,
						sortable: true,
					},
					{
						title: "更新时间",
						key: "updateTime",
						minWidth: 160,
						sortable: true,
					},
					{
						title: "操作",
						key: "action",
						align: "center",
						width: 120,
						render: (h, params) => {
							return h("div", [
								h(
									'I', {
										class: 'ivu-icon ivu-icon-ios-create-outline',
										style: {
											marginRight: "5px",
											color: "#2d8cf0",
											'font-size': "28px",
											'font-weight': "bold",
											cursor: "pointer"
										},
										attrs: {
											title: "编辑",

										},

										on: {
											click: () => {
												this.edit(params.row);
											}
										}
									},

								),

								h(
									'i', {
										class: 'ivu-icon ivu-icon-ios-trash',
										style: {
											marginRight: "5px",
											color: "#ff5959",
											'font-size': "28px",
											cursor: "pointer"
										},
										attrs: {
											title: "删除",
										},

										on: {
											click: () => {
												this.remove(params.row);
											}
										}
									},

								)
							]);
						}
					}
				],
				data: [], // 表单数据
				pageNumber: 1, // 当前页数
				pageSize: 10, // 页面大小
				total: 0, // 表单数据总数

			};
		},
		methods: {
			showImage(v) {
			  this.picTitle = v.hallNo + "(" + v.imageUrl + ")";
			  this.picVisible = true;
			  this.imageUrl = v.imageUrl;
			},
			init() {
				this.getDataList();

			},
			//手动输入 图片地址
			inputImage(e){
				this.uploadList=[{url:this.form.imageUrl}];
			},
			changePage(v) {
				this.searchForm.pageNumber = v;
				this.getDataList();
				this.clearSelectAll();
			},
			changePageSize(v) {
				this.searchForm.pageSize = v;
				this.getDataList();
			},
			handleSearch() {
				this.searchForm.pageNumber = 1;
				this.searchForm.pageSize = 10;
				this.getDataList();
			},
			handleReset() {
				this.$refs.searchForm.resetFields();
				this.searchForm.pageNumber = 1;
				this.searchForm.pageSize = 10;
				// 重新加载数据
				this.getDataList();
			},
			changeSort(e) {
				this.searchForm.sort = e.key;
				this.searchForm.order = e.order;
				if (e.order === "normal") {
					this.searchForm.order = "";
				}
				this.getDataList();
			},
			clearSelectAll() {
				this.$refs.table.selectAll(false);
			},
			changeSelect(e) {
				this.selectList = e;
				this.selectCount = e.length;
			},
			getDataList() {
				this.loading = true;
				getHallList(this.searchForm).then(res => {
					this.loading = false;
					if (res.success === true) {
						this.data = res.result.content;
						this.total = res.result.totalElements;
					}
				});


			},


			handleSubmit() {
				
				this.$refs.form.validate(valid => {
					
					if (valid) {
						
						this.submitLoading = true;

						if (this.modalType === 0) {
							// 添加 避免编辑后传入id等数据 记得删除
							delete this.form.id;

							addHall(this.form).then(res => {
								this.submitLoading = false;
								if (res.success == true) {
									this.$Message.success("操作成功");
									this.getDataList();
									this.modalVisible = false;
	 
									}
								});

						} else {
							// 编辑
							 editHall(this.form).then(res => {
							 	this.submitLoading = false;
							 	if (res.success == true) {
							 		this.$Message.success("操作成功");
							 		this.getDataList();
							 		this.modalVisible = false;
							 	}
							 });

						}
					}
				});
			},
			add() {
				if(this.$refs.upload){
					this.$refs.upload.clearFiles();
				}
				
				this.uploadList=[];
				this.modalType = 0;
				this.modalTitle = "添加";
				this.$refs.form.resetFields();
				delete this.form.id;
				this.modalVisible = true;
			},
			edit(v) {
				this.modalType = 1;
				this.modalTitle = "编辑";
				// 转换null为""
				for (let attr in v) {
					if (v[attr] === null) {
						v[attr] = "";
					}
				}
				let str = JSON.stringify(v);
				let data = JSON.parse(str);
				this.form = data;
				
				if(this.$refs.upload){
					this.$refs.upload.clearFiles();
				}
				this.uploadList=[{url:data.imageUrl}];
				this.modalVisible = true;
			},
			remove(v) {
				this.$Modal.confirm({
					title: "确认删除",
					// 记得确认修改此处
					content: "您确认要删除 " + v.hallNo + " ?",
					onOk: () => {
						// 删除
						this.operationLoading = true;
						deleteHall(v.id).then(res => {
							this.operationLoading = false;
							if (res.success == true) {
								this.$Message.success("删除成功");
								this.getDataList();
							}
						});


					}
				});
			},
			delAll() {
				if (this.selectCount <= 0) {
					this.$Message.warning("您还未选择要删除的数据");
					return;
				}
				this.$Modal.confirm({
					title: "确认删除",
					content: "您确认要删除所选的 " + this.selectCount + " 条数据?",
					onOk: () => {
						let ids = "";
						this.selectList.forEach(function(e) {
							ids += e.id + ",";
						});
						ids = ids.substring(0, ids.length - 1);
						this.operationLoading = true;
						deleteHall(ids).then(res => {
							this.operationLoading = false;
							if (res.success == true) {
								this.$Message.success("删除成功");
								this.clearSelectAll();
								this.getDataList();
							}
						});
					}
				});
			},
			handleSuccess(res, file) {
				if (res.success == true) {
					file.url = res.result;
					this.form.imageUrl = res.result;
					
					this.uploadList=[{url:res.result}];
					this.$refs.upload.clearFiles();
				} else {
					this.$refs.upload.clearFiles();
					this.$Message.error(res.message);
				}
			},
			handleError(error, file, fileList) {
				this.$Message.error(error.toString());
			},
			handleFormatError(file) {
				this.$Notice.warning({
					title: "不支持的文件格式",
					desc: "所选文件‘ " +
						file.name +
						" ’格式不正确, 请选择 .jpg .jpeg .png .gif格式文件"
				});
			},
			handleMaxSize(file) {
				this.$Notice.warning({
					title: "文件大小过大",
					desc: "所选文件‘ " + file.name + " ’大小过大, 不得超过 5M."
				});
			},
			handleBeforeUpload() {
				const check = this.uploadList.length < 2;
				if (!check) {
					this.$Notice.warning({
						title: "最多只能上传 1 张图片"
					});
				}
				return check;
			},
		},
		computed: {},
		mounted() {
			this.accessToken = {
				accessToken: this.getStore("accessToken")
			};
			
			this.init();
		}
	};
</script>
<style lang="less">
	.search {
		.operation {
			margin-bottom: 2vh;
		}

		.select-count {
			font-size: 13px;
			font-weight: 600;
			color: #40a9ff;
		}

		.select-clear {
			margin-left: 10px;
		}

		.page {
			margin-top: 2vh;
		}

		.drop-down {
			font-size: 13px;
			margin-left: 5px;
		}
	}

</style>
